using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Modules.NBrightEspace.Components;
using DotNetNuke.Services.Exceptions;
using NBrightCore.common;
using NBrightCore.render;
using NBrightDNN;

namespace DotNetNuke.Modules.NBrightEspace
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditNBrightEspace class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Clients : EspaceModuleBase
    {

        #region Event Handlers

        private const string EntityTypeCode = "CLIENT"; // change for DB records


        override protected void OnInit(EventArgs e)
        {
            //Set base EntityTypeCode, MUST be done for all NBright child ctrls before OnInit
            base.EntityTypeCode = EntityTypeCode;
            
            base.OnInit(e);
            
            //initalize the repeater template based on what we want to see, a list or editing details.
            if (base.ItemId=="")
            {// itemid is blank so display the list
                rpData.Visible = false;

                //All list display functions are processed via the parent class, we just initiallize here.
                base.OnInitActivateList(true, true, MapPath(ControlPath));

            }
            else
            {// itemid is not blank, so display the detail template.
                rpData.ItemTemplate = new GenXmlTemplate(TemplCtrl.GetTemplateData(EntityTypeCode + "_Detail.html", Utils.GetCurrentCulture()));
            }

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Page.IsPostBack == false)
            {
                PageLoad();
            }
        }

        private void PageLoad()
        {
            try
            {
                if (base.ItemId=="")
                {// display list        

                    //set default filter
                    if (String.IsNullOrEmpty(UInfo.SearchClearAfter))
                    {
                        UInfo.SearchFilters = " and (([xmlData].value('(genxml/radiobuttonlist/rbltype)[1]', 'nvarchar(10)') collate Latin1_General_CI_AI = '1')) ";
                        UInfo.SearchOrderby = " Order by [xmlData].value('(genxml/textbox/txtcompanyname)[1]', 'nvarchar(50)') ";
                        UInfo.Save();
                    }

                    base.BindListData();
                }
                else
                {// display the detail
                    base.DoDetail(rpData);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }



        #endregion

        #region  "Events "

        protected void CtrlItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

            switch (e.CommandName.ToLower())
            {
                case "new":
                    Response.Redirect(EditUrl("itemid", "0", EntityTypeCode), true);
                    break;
                case "updateexit":
                    UpdateData();
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "update":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
                case "addlog":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
                case "cancel":
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "delete":
                    base.DeleteData(rpData);
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "createtask":
                    UpdateData();
                    UInfo.SelItemId = cArg; //save so new taks is linked to this item.
                    UInfo.Save();
                    var strParams = new string[] {"selectid=1"}; // set selectid param, so client updates into task.
                    Response.Redirect(EditUrl("itemid", "0", "Tasks", strParams), true);
                    break;
                case "gotasks":
                    UpdateData();
                    UInfo.SearchFilters = " and (([xmlData].value('(genxml/hidden/clientid)[1]', 'nvarchar(50)') collate Latin1_General_CI_AI = '" + base.ItemId + "')) ";
                    UInfo.Save();
                    Response.Redirect(EditUrl("Tasks"), true);
                    break;
                case "printreport":
                    Response.Clear();
                    Response.Buffer = false;
                    Response.BufferOutput = false;
                    var objCtrl = new EspaceController();
                    Response.Write(objCtrl.GetClientReport(Convert.ToInt32(base.ItemId), Utils.GetCurrentCulture()));
                    Response.Flush();
                    Response.End();
                    break;

            }

        }

        #endregion

        #region "presistance methods"


        private void UpdateData()
        {
                if (Page.IsValid)
                {
                    // Does standard update of template form
                    var objInfo = (NBrightInfo)base.UpdateDetailNoValidate(rpData, EntityTypeCode,"");

                    // Do any special updates that are required.
                    if (string.IsNullOrEmpty(GenXmlFunctions.GetField(rpData, "txtClientRef")))
                    {
                        //if ClientRef doesn't exist create it
                        var objCtrl = new EspaceController();
                        GenXmlFunctions.SetField(rpData, "txtClientRef", "CL3" + objInfo.ItemID.ToString("000000") + "-" + Convert.ToString(DateTime.Now.Year).Substring(2, 2));
                        objInfo.XMLData = GenXmlFunctions.GetGenXml(rpData);
                        objCtrl.Update(objInfo);
                    }
                }
        }



        #endregion


    }

}